/**
 * 用户列表适配器
 */
package com.xiaomuwu.android.ui.shared

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.xiaomuwu.android.R
import com.xiaomuwu.android.XiaoMuWuApplication
import com.xiaomuwu.android.logic.model.User
import com.xiaomuwu.android.ui.Displayer
import com.xiaomuwu.android.ui.ForSearch

class UserListAdapter(private val userList:List<User>) :
    RecyclerView.Adapter<UserListAdapter.ViewHolder>() {

    inner class ViewHolder(view: View):RecyclerView.ViewHolder(view) {
        val userName: TextView = view.findViewById(R.id.user_Name)  // 用户名
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view= LayoutInflater.from(parent.context)
            .inflate(R.layout.user_item,parent,false)
        val viewHolder=ViewHolder(view)

        // 用户列表项点击监听
        viewHolder.itemView.setOnClickListener{
            val position=viewHolder.adapterPosition
            ForSearch.userID=userList[position].id  // 设置用户详情页ID
//            Displayer.page=1  // test:实现从用户详情页返回后滚动到原来的浏览位置
            Displayer.pprevPageStatus=Displayer.prevPageStatus
            Displayer.prevPageStatus=Displayer.pageStatus
            Displayer.pageStatus="UserDetail"
            Displayer.userID=userList[position].id  // 更新用户ID
            Displayer.userName=userList[position].name  // 更新用户名

            // 发送显示用户详情广播
            val intent= Intent("com.xiaomuwu.android.ShowUserDetail")
            XiaoMuWuApplication.context.sendBroadcast(intent)
        }
        return viewHolder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val res=userList[position]
        holder.userName.text=res.name   // 设置用户名
    }

    override fun getItemCount(): Int =userList.size

}